package rpc.sync;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import common.ServerChannel;
import proxy.IProxyFactory;
import proxy.JdkProxyFactory;
import serialization.ISerialize;

public class RpcClassRef<T> implements InvocationHandler{
	
	private IProxyFactory proxyFactory;
	
	private T t;
	
	private Class<T> interfaceClass;
	
	private ServerChannel channel;
	
	private ISerialize serialize;
	
	public RpcClassRef(ServerChannel channel,IProxyFactory proxyFactory,ISerialize serialize)
	{
		this.proxyFactory = proxyFactory;
		this.serialize = serialize;
		this.channel = channel;
	}
	
	public RpcClassRef() {
	}
	
	
	public T newRef()
	{
		return proxyFactory.getProxy(interfaceClass, this);
	}
	
	public T getRef()
	{
		T t = this.t;
		if(t!=null)
			return t;
		synchronized (proxyFactory) {
			t = this.t;
			if(t!=null)
				return t;
			t = newRef();
			this.t = t;
			return t;
		}
	}




	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String methodName = method.getName();
		//处理烦人的父类方法
		switch (methodName) {
		case "equals":
			return proxy == args[0];
		case "hashCode":
			return hashCode();
		case "toString":
			return toString();
		default:
			break;
		}
		//封装成 请求消息对象
		
//		Object message = populateMethodInvokerMessage(method, args, serviceRef);
//		return CompletableFuture.class.isAssignableFrom(method.getReturnType())
//				? invokeAsync(message, serviceRef, method) : invokeSync(message, serviceRef, method);
		// 调用被代理的对象的方法
		return null;
	}
	
	public static void main(String[] args) {
		RpcClassRef rf = new RpcClassRef<>();
		rf.interfaceClass = IProxyTest.class;
		rf.proxyFactory = new JdkProxyFactory();
		IProxyTest test = (IProxyTest)rf.newRef();
		
		System.out.println(test.toString());
		test.aa(66);
	}
	
}
